package org.csu.chatroom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.csu.chatroom.entity.User;
import org.csu.chatroom.persistence.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/login")
    public String showLoginPage() {
        return "login";  // 返回 login.html 页面
    }

    @PostMapping("/login")
    public String handleLogin(@RequestParam String username, @RequestParam String password, Model model, HttpSession session) {
        // 查询数据库中的用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        System.out.println(user);
        if (user != null && user.getPassword().equals(password)) {
            session.setAttribute("user", user);  // 登录成功，保存用户信息到 Session
            model.addAttribute("user", user);  // 登录成功，保存用户信息
            return "redirect:/chat-home";  // 跳转到聊天室主页
        } else {
            model.addAttribute("error", true);  // 登录失败
            return "login";  // 返回登录页面
        }
    }
}
